<?php
// 应用公共文件
use JPush\Client as JPush;
use \think\Db;

function push($uid,$param = ['type'=>'','message'=>'','parameters'=>'','status'=>'']){
    /*
     *
     * type 1 = 用户，2=跑侠
     * message  消息
     * parameters 订单号或其他一些参数
     * status 1 = 跑男提现结果 ,2 = 用户认证结果,3 = 用户退款,4 = 跑男抢单提醒, 5= 用户订单提醒,6=获得优惠券提醒,7=私人订单（调度）,8=系统后台推送消息
     *
     */
    try{
        vendor('jpush.autoload');
        $app = Db::table('push_config')->where('id',1)->find();
        $client = new JPush($app['appkey'], $app['appsecret']);
        $response = $client->push();
        if($uid != ''){
            $response->addAlias($uid);
        }else{
            $response->addAllAudience();
        }
        $response->setPlatform(array('ios', 'android'))->message($param)->send();
        return true;
    } catch (\JPush\Exceptions\APIConnectionException $e) {
        return false;
    } catch (\JPush\Exceptions\APIRequestException $e) {
        return false;
    }
}

function insert_message($uid,$title = '', $message = '', $type = '', $parameters = '')
{
    /*
     *
     * title = 标题
     * type 1 = 跑男提现结果 ,2 = 用户认证结果,3 = 用户退款,4 = 跑男抢单提醒, 5= 用户订单提醒,6=获得优惠券提醒,7=私人订单（调度）
     * message  消息
     * parameters 订单号或其他一些参数
     *
     */
    $time = time();
    Db::table('message')->insert(['uid'=>$uid,'title'=>$title,'message'=>$message,'type'=>$type,'parameters'=>$parameters,'time'=>$time]);
}

function redirect($url){
	header('Location:'.$url);
}

function Admin_auth(){
	$uid = session('wmo2o_a_uid');
	$pid = session('wmo2o_a_pid');
	$auth = session('wmo2o_a_auth');
	$type = session('wmo2o_a_type');
	$username = session('wmo2o_a_username');
	if(!empty($uid) && !empty($auth) && !empty($type) && !empty($username)){
		if(time()-session('wmo2o_a_time')>3600){
			session('wmo2o_a_uid',null);
			session('wmo2o_a_pid',null);
			session('wmo2o_a_category',null);
			session('wmo2o_a_auth',null);
			session('wmo2o_a_type',null);
			session('wmo2o_a_username',null);
			session('wmo2o_a_time',null);
			redirect(url('/admin/login'));
			exit;
		}else{
			if($type=='1'){
				$admin = db('admini')->where(['id'=>$uid,'username'=>$username,'auth'=>$auth])->find();
			}
			if($type=='2'){
				$admin = db('admini')->where(['id'=>$uid,'username'=>$username,'pid'=>$pid,'auth'=>$auth])->find();
				if(input('pid')){
					if(!in_array(input('pid'),explode(',',session('wmo2o_a_pid')))){
						exit;
					}
				}
				if(input('cid')){
					if(!in_array(input('cid'),explode(',',session('wmo2o_a_pid')))){
						exit;
					}
				}
				if(input('aid')){
					if(!in_array(input('aid'),explode(',',session('wmo2o_a_pid')))){
						exit;
					}
				}
			}
			if(!$admin){
				redirect(url('/admin/login'));	
				exit;
			}
			session('wmo2o_a_time',time());
			$request = \think\Request::instance();
			$auth = explode(',',str_replace("|",",",$auth));
			if($request->action()!="ajax_get" && $request->controller()!="Material"){
				if(!in_array(strtolower($request->controller().'/'.$request->action()),$auth)){
					$authname = db('admin_menu')->wherelike('auth','%'.strtolower($request->controller().'/'.$request->action()).'%')->value('name');
					db('Illegal')->insert(['username'=>$username,'authname'=>$authname,'ip'=>get_onlineip(),'time'=>date("Y-m-d H:i"),]);
					exit("<div style='text-align: center;font-family: Microsoft yahei;width: 500px;margin: auto;margin-top:10%'><h1 style='color:red;text-align:center'>警告：您没有权限访问此页面!</h1>我们已经记录下您的相关信息：<br>IP:".get_onlineip()."<br/>用户名：".$username."<br/>时间：".date("Y-m-d H:i")."<br/><br/><strong style='color:red;text-align:center'>请合法操作！且行且珍惜！</strong></div>");
					exit;
				}
			}
		}		
	}else{
		redirect(url('/admin/login'));	
		exit;
	}
}

function pages($table,$where = array(),$page = 1){
	if(!$page || $page == 0){$page=1;}
	$list_rows = config('paginate.list_rows');
	$limit = ($page-1) * $list_rows;
	$total = db($table)->where($where)->whereIn('pid',session('wmo2o_a_pid'))->count();
	$pagetotal = ceil($total/$list_rows);
	return array('limit'=>$limit.",".$list_rows,'pages'=>['page'=>$page,'pagetotal'=>$pagetotal,'total'=>$total]);
}

function success($msg = '',$redirecturl = ''){
	return view('public/success',['msg'=>$msg,'url'=>$redirecturl]);
}

function error($msg = '',$redirecturl = ''){
	return view('public/error',['msg'=>$msg,'url'=>$redirecturl]);
}

function get_onlineip() { 
	$ch = curl_init('http://city.ip138.com/ip2city.asp'); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	$a = curl_exec($ch); 
	preg_match('/\[(.*)\]/', $a, $ip); 
	return $ip[1];
} 

function seller_auth(){
	$uid = session('wmo2o_u_uid');
	$type = session('wmo2o_u_type');
	$phone = session('wmo2o_u_phone');
	if(!empty($uid) && !empty($type) && !empty($phone)){
		if(time()-session('wmo2o_u_time')>3600){
			session('wmo2o_u_uid',null);
			session('wmo2o_u_type',null);
			session('wmo2o_u_phone',null);
			session('wmo2o_u_time',null);
			redirect(url('/seller/login'));
			exit;
		}else{
			$user = db('user')->where(['id'=>$uid,'phone'=>$phone,'type'=>$type])->find();
			if(!$user){
				redirect(url('/seller/login'));	
				exit;
			}
			session('wmo2o_u_time',time());
			$config = db('webconfig')->where('id',1)->find();
			config('website',$config);
		}		
	}else{
		redirect(url('/seller/login'));	
		exit;
	}
}

function user_auth(){
	$uid = session('wmo2o_u_uid');
	$type = session('wmo2o_u_type');
	$phone = session('wmo2o_u_phone');
	if(!empty($uid) && !empty($type) && !empty($phone)){
		if(time()-session('wmo2o_u_time')>3600){
			session('wmo2o_u_uid',null);
			session('wmo2o_u_type',null);
			session('wmo2o_u_phone',null);
			session('wmo2o_u_time',null);
			redirect(url('/index/login'));
			exit;
		}else{
			$user = db('user')->where(['id'=>$uid,'phone'=>$phone,'type'=>$type])->find();
			if(!$user){
				redirect(url('/index/login'));	
				exit;
			}
			session('wmo2o_u_time',time());
		}		
	}else{
		redirect(url('/index/login'));	
		exit;
	}
}

function get_name($uid){
	return db("user")->where(['id'=>$uid,'type'=>1])->value('name');
}

function get_catname($gid,$cateid){
	/*if($cateid){
		return db("service_category")->where(['id'=>$gid])->value('title')."-".db("service_category")->where(['id'=>$cateid])->value('title');
	}else{*/
		return db("service_category")->where(['id'=>$gid])->value('title');
	//}
}
